package com.kun.companion.core.ui.component;

import cn.hutool.core.util.StrUtil;
import com.kun.companion.core.http.DeepSeekService;
import com.kun.companion.core.queue.ui.button.AwaitEventButton;
import com.kun.companion.core.ui.control.BaseTextArea;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;

import java.math.BigDecimal;

/**
 * TODO
 *
 * @author gzc
 * @since 2025/3/1 8:05
 **/
public class AiChatContainer extends BorderPane {
    /**
     * 区域尺寸比例常量
     */
    private static final BigDecimal OUTPUT_BOX_WIDTH_RATIO = BigDecimal.valueOf(0.8D);
    /**
     * 输出框容器
     */
    private final AiChatPane outputBox = new AiChatPane();
    /**
     * 输入框容器
     */
    private final VBox inputBox = new VBox();
    private final BaseTextArea inputTextArea = new BaseTextArea("给坤坤发送消息吧", true);
    private final HBox buttonBox = new HBox();
    private final AwaitEventButton sendButton = new AwaitEventButton("发送");

    public AiChatContainer() {
        initComponentLayout();
        registerListeners();
        initInteractions();
    }

    private void initComponentLayout() {
        buttonBox.getChildren().addAll(sendButton);
        inputBox.getChildren().addAll(inputTextArea, buttonBox);
        setCenter(outputBox);
        setBottom(inputBox);
    }

    private void registerListeners() {
        // 尺寸变化监听
        widthProperty().addListener((obs, old, newVal) -> updateDimensions(newVal.doubleValue(), getHeight()));
        heightProperty().addListener((obs, old, newVal) -> updateDimensions(getWidth(), newVal.doubleValue()));
    }

    protected void updateDimensions(double width, double height) {
        double updateHeight = BigDecimal.valueOf(height).multiply(OUTPUT_BOX_WIDTH_RATIO).doubleValue() - 5;
        outputBox.setPrefSize(width, updateHeight);
        inputBox.setPrefSize(width, BigDecimal.valueOf(height).subtract(new BigDecimal(updateHeight)).doubleValue() - 5);
    }

    private void initInteractions() {
        sendButton.action(() -> {
            String inputText = inputTextArea.getText();
            if (StrUtil.isBlank(inputText)) {
                return;
            }
            String result = DeepSeekService.sendAndResult(inputText);
            outputBox.startTyping(result);
        });
    }


}
